﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BikeManageBusiness.logical;
using Data.Common;
using Data.Enum;
using Data.Model;
using Data.ViewModel;
using DataAccess.AccountManage;
using DataAccess.BikeManage.logical;
using Ninject;
using WinForm.Helper;

namespace WinForm.UserManage
{
    public partial class ReSaveCpuCardFrm : Form
    {
        private static readonly IKernel Kernel = new StandardKernel(new DbModule());
        private readonly IAccount _account = Kernel.Get<IAccount>();
        private readonly IBusinesses _business = Kernel.Get<IBusinesses>();

        public ReSaveCpuCardFrm()
        {
            InitializeComponent();
        }

        private void RefreshData()
        {
            GC.Collect();
            string errorString = string.Empty;
            ResultInfo<PagingDataSet<jsh_account>> accounts = _account.GetAccounts(1, Int32.MaxValue, null,
                                                                                           textBoxX1.Text, null);
            if (accounts.ResultNumber == ResultEnum.Success && accounts.Obj != null)
            {
                try
                {
                    int searil = 0;
                    List<AccountView> views = new List<AccountView>();
                    foreach (jsh_account a in accounts.Obj.Records)
                    {
                        searil++;
                        views.Add(new AccountView()
                        {
                            CpuNo = a.cpuno,
                            BeginDate = Converts.ConvertToNormalDate(a.khdate),
                            CurrentMoney = a.balance,
                            IdCardType = a.zzlx,
                            IdNo = a.zzhm,
                            Phone = (string.IsNullOrEmpty(a.telephone) ? a.mobile : a.telephone),
                            Sex = a.sex,
                            UserName = a.username,
                            ValideDate = Converts.ConvertToNormalDate(a.validate),
                            Serial = searil,
                            Id = a.id,
                            Status = a.status
                        });
                    }
                    dataGridView1.DataSource = views;

                    tabItem1.Visible = false;
                    tabItem2.Visible = true;
                }
                catch (Exception)
                {
                    dataGridView1.DataSource = accounts.Obj.Records;
                }
            }
            else
            {
                errorString += accounts.Describe;
            }
            GC.Collect();
            if (!string.IsNullOrEmpty(errorString))
            {
                MyMessageBox.ShowMessageBoxInfo(errorString);
            }
        }

        private void buttonX1_Click(object sender, EventArgs e)
        {
            string errorString = string.Empty;
            try
            {
                GC.Collect();
                Dkqa16dLogical dkqa16DLogical = new Dkqa16dLogical();
                ResultInfo<IDCardData> iddata = dkqa16DLogical.GetIdCardData();
                if (iddata.ResultNumber == ResultEnum.Success)
                {
                    textBoxX1.Text = iddata.Obj.IDCardNo;
                }

                if (string.IsNullOrEmpty(textBoxX1.Text))
                {
                    errorString += "  请将身份证放入读卡器或者填入身份证号码！";
                }
                else
                {
                    RefreshData();
                }
            }
            catch (Exception e1)
            {
                errorString += e1.Message;
            }
            GC.Collect();
            if (!string.IsNullOrEmpty(errorString))
            {
                MyMessageBox.ShowMessageBoxInfo(errorString);
            }
        }

        private void buttonX2_Click(object sender, EventArgs e)
        {
            tabItem1.Visible = true;
            tabItem2.Visible = false;
        }

        private void buttonX3_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            try
            {
                GC.Collect();
                if (dataGridView1.SelectedRows.Count != 1)
                {
                    errorMessage = errorMessage + "只能选择一条数据进行操作";
                }
                else
                {
                    long accountid = Convert.ToInt64(dataGridView1.SelectedRows[0].Cells["id"].Value);
                    ResultInfo<bool> logouta = _account.UpdateAccountStatus(accountid, CpuCardStatus.Logout);
                    if (logouta.ResultNumber == ResultEnum.Success)
                    {

                        jsh_account oldaccount = _account.GetAccount(accountid);
                        if (oldaccount != null && oldaccount.id > 0)
                        {
                            #region 新建用户
                            try
                            {
                                var zq58Logical = new Zq58Logical();
                                ResultInfo<string> checkcpu = zq58Logical.CheckCpuEquipment();
                                if(checkcpu.ResultNumber==ResultEnum.Success)
                                {
                                    //获取cpu卡用户信息
                                    var cpuAccount = new CpuAccount { CpuCardNo = checkcpu.Obj };
                                    cpuAccount.CpuCardVersion = oldaccount.ver;
                                    cpuAccount.CpuCardStatus = CpuCardStatus.Open;
                                    cpuAccount.CpuCardType = oldaccount.cardtype;
                                    cpuAccount.DisplayName = oldaccount.username;
                                    cpuAccount.Fee = "";
                                    cpuAccount.Address = oldaccount.addr1;
                                    cpuAccount.IdCardNo = oldaccount.zzhm;
                                    cpuAccount.IdCardType = oldaccount.zzlx;
                                    cpuAccount.Mobile = oldaccount.mobile;
                                    cpuAccount.Phone = oldaccount.telephone;
                                    cpuAccount.Sex = oldaccount.sex;
                                    cpuAccount.Nation = oldaccount.nation;

                                    ResultInfo<byte[]> writeAccount = zq58Logical.WriteAccountInfo(cpuAccount);
                                    if (writeAccount.ResultNumber == ResultEnum.Success)
                                    {
                                        ResultInfo<byte[]> borroBike =
                                            zq58Logical.WriteBorrowBikeInfo(new BorrowBike
                                            {
                                                OpenAccountDate = Converts.ConvertDateToString(DateTime.Now),
                                                EndAccountDate = Converts.ConvertDateToString(DateTime.Now.AddYears(3))
                                            });
                                        //这里是指为了写开户日期跟有效期
                                        if (borroBike.ResultNumber == ResultEnum.Success)
                                        {
                                            ResultInfo<Decimal> initialMoney = zq58Logical.QueryPurse();
                                            if(initialMoney.ResultNumber==ResultEnum.Success)
                                            {
                                                //清空原本卡中的余额
                                                ResultInfo<byte[]> cleanMoney = zq58Logical.CostMoney(initialMoney.Obj);
                                                if(cleanMoney.ResultNumber==ResultEnum.Success)
                                                {
                                                    ResultInfo<byte[]> purseMoney = zq58Logical.PurseSave(oldaccount.balance);
                                                    if (purseMoney.ResultNumber == ResultEnum.Success)
                                                    {
                                                        ResultInfo<Decimal> queryMoney = zq58Logical.QueryPurse();
                                                        if (queryMoney.ResultNumber == ResultEnum.Success)
                                                        {
                                                            //保存到数据库之前先查询用户卡的信息
                                                            ResultInfo<CpuAccount> newAccount = zq58Logical.ReadAccountInfo();
                                                            if (newAccount.ResultNumber == ResultEnum.Success)
                                                            {
                                                                //将信息存入数据库
                                                                try
                                                                {
                                                                    var jshAccount = oldaccount;
                                                                    jshAccount.cpuno = checkcpu.Obj;
                                                                    jshAccount.cpuid = checkcpu.Obj;
                                                                    jshAccount.status = CpuCardStatus.Open;

                                                                    ResultInfo<bool> openAccount = _account.OpenAccount(jshAccount,
                                                                        0,
                                                                        0,
                                                                        0, SystemInfo.OperateAddress,
                                                                        SystemInfo.OperateAddressId, SystemInfo.OperatePsamId);
                                                                    if (openAccount.ResultNumber == ResultEnum.Success)
                                                                    {
                                                                        if (openAccount.Obj)
                                                                        {
                                                                            //工单
                                                                            int bsid= _business.AddBusiness(new Business() {businessname="补卡",businesstype = 11,operateaddress = SystemInfo.OperateAddress,operateaddressid = SystemInfo.OperateAddressId,operateid = SystemInfo.OperateId,operatepsamid = SystemInfo.OperatePsamId,operatetable = "jsh_account",operatetime = DateTime.Now });
                                                                            if(bsid>0)
                                                                            {
                                                                                if (
                                                                                MyMessageBox.ShowMessageBoxQuestion(
                                                                                    string.Format("补卡成功！账户当前金额为：{0}元",
                                                                                        queryMoney.Obj)) ==
                                                                                DialogResult.Yes)
                                                                                {
                                                                                    Dispose();
                                                                                }
                                                                            }else
                                                                            {
                                                                                errorMessage += "补卡工单插入失败！";
                                                                            }
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        //如果存入数据库没有成功，扣除刚刚充值到cpu卡的钱
                                                                        ResultInfo<byte[]> backMoney =
                                                                            zq58Logical.CostMoney(oldaccount.balance);
                                                                        if (backMoney.ResultNumber != ResultEnum.Success)
                                                                        {
                                                                            errorMessage = errorMessage + backMoney.Describe;
                                                                        }
                                                                        errorMessage = errorMessage + openAccount.Describe;
                                                                    }
                                                                }
                                                                catch (Exception e1)
                                                                {
                                                                    errorMessage = errorMessage + e1.Message;
                                                                }
                                                            }
                                                            else
                                                            {
                                                                errorMessage = errorMessage + newAccount.Describe;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            errorMessage += queryMoney.Describe;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        errorMessage = errorMessage + purseMoney.Describe;
                                                    }
                                                }else
                                                {
                                                    errorMessage += cleanMoney.Describe;
                                                }
                                            }else
                                            {
                                                errorMessage += initialMoney.Describe;
                                            }
                                        }
                                        else
                                        {
                                            errorMessage = errorMessage + borroBike.Describe;
                                        }
                                    }
                                    else
                                    {
                                        errorMessage = errorMessage + writeAccount.Describe;
                                    }
                                }else
                                {
                                    errorMessage += checkcpu.Describe;
                                }
                            }
                            catch (Exception e1)
                            {
                                errorMessage = errorMessage + e1.Message;
                            }
                            if (!string.IsNullOrEmpty(errorMessage))
                            {
                                MyMessageBox.ShowMessageBoxError(errorMessage);
                            }
                            GC.Collect();
                            #endregion
                        }
                        else
                        {
                            errorMessage += "没有找到相关用户，请重新选择！";
                        }
                    }
                    else
                    {
                        errorMessage += logouta.Describe;
                    }
                }
            }
            catch (Exception e1)
            {
                errorMessage = errorMessage + e1.Message;
            }
            GC.Collect();
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }

    }
}
